package com.ABdolphin.forum.controller;

import com.ABdolphin.forum.common.AppResult;
import com.ABdolphin.forum.common.ResultCode;
import com.ABdolphin.forum.config.AppConfig;
import com.ABdolphin.forum.model.User;
import com.ABdolphin.forum.services.IUserService;
import com.ABdolphin.forum.services.impl.UserServiceImpl;
import com.ABdolphin.forum.utils.MD5Util;
import com.ABdolphin.forum.utils.StringUtil;
import com.ABdolphin.forum.utils.UUIDUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/user")
@Tag(name = "USER")
@Slf4j
public class UserController {
    @Resource(type = UserServiceImpl.class)
    private IUserService userService;

    @PostMapping("/register")
    @Operation(summary = "注册")
    public AppResult register(@Parameter(name = "userName" ,description = "用户名称")@RequestParam("userName")@NotNull String userName,
                              @Parameter(name = "nickname",description = "昵称")@RequestParam("nickname")@NotNull String nickname,
                              @Parameter(name = "password",description = "密码")@RequestParam("password")@NotNull String password,
                              @Parameter(name = "passwordRepeat",description = "再次确认密码")@RequestParam("passwordRepeat")@NotNull String passwordRepeat){
        if (!password.equals(passwordRepeat)){
            log.info(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.fail(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        User userInsert=new User();
        userInsert.setUserName(userName);
        userInsert.setNickname(nickname);
        String salt = UUIDUtil.UUID_32();
        String MD5Password = MD5Util.md5(password, salt);
        userInsert.setPassword(MD5Password);
        userInsert.setSalt(salt);
        userService.createNormalUser(userInsert);
        log.info("用户注册成功:用户名称为: "+userName);
        return AppResult.success();
    }
    @PostMapping("/login")
    @Operation(summary = "登录")
    public AppResult login(HttpServletRequest request,
                           @Parameter(name = "userName",description = "姓名")@RequestParam("userName")@NotNull String userName,
                           @Parameter(name = "password",description = "密码")@RequestParam("password")@NotNull String password){
        User user = userService.login(userName, password);
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION,user);
        return AppResult.success();
    }

    @PostMapping("/logout")
    @Operation(summary = "注销")
    public AppResult login(HttpServletRequest request){
        HttpSession session = request.getSession();
        if(session!=null){
            session.invalidate();
        }
        return AppResult.success();
    }
    @GetMapping("/info")
    @Operation(summary = "个人信息查询")
    public AppResult<User> info(HttpServletRequest request,
                                @Parameter(name = "id" ,description = "用户id")@RequestParam(value = "id",required = false) Long id){
        if (id==null){
            HttpSession session = request.getSession(false);
            User user =(User) session.getAttribute(AppConfig.USER_SESSION);
            id=user.getId();
        }
        if (id<=0){
            log.info("id小于等于0,无效参数,id={}",id);
            return AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        User user = userService.selectById(id);
        if (user==null||user.getDeleteState()==1){
            log.info("user为空,或用户已注销");
            return AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return AppResult.success(user);
    }
    @PostMapping("/modifyInfo")
    @Operation(summary = "修改个人信息")
    public AppResult<User> modifyInfo(HttpServletRequest request,
                                      @Parameter(name = "userName",description = "姓名")@RequestParam(value = "userName",required = false)  String userName,
                                      @Parameter(name = "nickname",description = "昵称")@RequestParam(value = "nickname",required = false) String nickname,
                                      @Parameter(name = "gender",description = "性别")@RequestParam(value = "gender",required = false) Byte gender,
                                      @Parameter(name = "email",description = "邮箱")@RequestParam(value = "email",required = false)String email,
                                      @Parameter(name = "phoneNum",description = "电话")@RequestParam(value = "phoneNum",required = false)String phoneNum,
                                      @Parameter(name = "remark",description = "个人简介")@RequestParam(value = "remark",required = false)String remark){
        if (StringUtil.isEmpty(userName) && StringUtil.isEmpty(nickname)
                && gender==null && StringUtil.isEmpty(email)
                && StringUtil.isEmpty(phoneNum) && StringUtil.isEmpty(remark)){
            return AppResult.fail("请输入要修改的内容");
        }
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUserName(userName);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);
        userService.modifyInfo(updateUser);
        User selectByIdUser = userService.selectById(user.getId());
        session.setAttribute(AppConfig.USER_SESSION,selectByIdUser);
        return AppResult.success(selectByIdUser);
    }
    @PostMapping("/modifyPwd")
    @Operation(summary = "修改密码")
    public AppResult modifyPwd(HttpServletRequest request,
                               @Parameter(name = "oldPassword" ,description = "初始密码")@RequestParam("oldPassword")@NotNull String oldPassword,
                               @Parameter(name = "newPassword" ,description = "新密码")@RequestParam("newPassword")@NotNull String newPassword,
                               @Parameter(name = "passwordRepeat" ,description = "确认新密码")@RequestParam("passwordRepeat")@NotNull String passwordRepeat){
        //两次输入的新密码是否一致
        if (!newPassword.equals(passwordRepeat)){
            log.info(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.fail(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //修改密码
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        userService.modifyPassword(user.getId(), oldPassword,newPassword);
        //更新session
        User resultUser = userService.selectById(user.getId());
        session.setAttribute(AppConfig.USER_SESSION,user);
        if (session!=null){
            session.invalidate();
        }
        return AppResult.success();
    }
    @PostMapping(value = "/modifyAvatar",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Operation(summary = "修改头像")
    public AppResult modifyAvatar(HttpServletRequest request,
                                  @Parameter(name = "file",description = "头像文件",
                                          content = @Content(mediaType = MediaType.APPLICATION_OCTET_STREAM_VALUE,
                                                  schema = @Schema(type = "image", format = "binary")))
                                  @RequestParam("avatar")MultipartFile file){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        String avatarUrl="";
        try {
            avatarUrl=userService.modifyImage(user.getId(), file);
        }catch (Exception e){
            log.error(e.getMessage());
            return AppResult.fail(e.getMessage());
        }
        log.info(ResultCode.SUCCESS.toString()+"头像更新成功");
        return AppResult.success(avatarUrl);
    }
}
